package com.baizhi.cmfz.aspect;


import com.baizhi.cmfz.annotation.LogAnnotation;
import com.baizhi.cmfz.dao.CmfzLogDao;
import com.baizhi.cmfz.entity.Admin;
import com.baizhi.cmfz.entity.CmfzLog;
import com.baizhi.cmfz.service.ActiveService;
import com.baizhi.cmfz.util.IpAddrressUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;


@Configuration
@Aspect
public class LogEnhance {
	@Resource
	private CmfzLogDao cmfzLogDao;

	@Resource
	private ActiveService activeService;

	@Resource
	private ObjectMapper objectMapper;


//	配置后置曾强

	//定义切入点
	@After("@annotation(com.baizhi.cmfz.annotation.LogAnnotation)")
	public void logAfter(JoinPoint joinPoint) throws JsonProcessingException {
//		1.获取日志对象
		CmfzLog cmfzLog = new CmfzLog();

//		2.为对象的属性赋值
		cmfzLog.setLogDate(new Date());

//		3.获取session对象
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
//		HttpSession session = request.getSession();

		Session session = SecurityUtils.getSubject().getSession();

//		4.获取admin对象
		Admin admin = (Admin) session.getAttribute("admin");

//		5.设置cmfzLog的id
		cmfzLog.setAdminId(admin.getAdminId());

//		6.获取请求的ip地址
//		String remoteHost = request.getRemoteHost(); 或者使用工具类
		String ipAdrress = IpAddrressUtil.getIpAdrress(request);
		cmfzLog.setLogIp(ipAdrress);

//		7.获取请求的方法的方法签名
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

//		8.通过方法对象获得方法上的注解
		LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
//		注解valuer的值
		String value = annotation.value();
//		注解的type值
		String type = annotation.type();
		cmfzLog.setLogContent(value);
		cmfzLog.setLogType(type);

		String s = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(cmfzLog);

		activeService.mqProduct(s);

//		 9.将对象添加到数据库
//		cmfzLogDao.insertCmfzLog(cmfzLog);
	}
}
